package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static   SecretKey signingKey = Keys.hmacShaKeyFor("x#eSA%pmy@FVsL7iN1ikVy1CpGxPoOYo".getBytes());

    /* 创建token
     *   token中保存登录用户的身份信息
     * */

    public static String createToken(String userName,Long userId){
//3600000*24*365
        String token = Jwts.builder()

                .setSubject("lease-login")       //token的主题(token的类型)
                .setExpiration(new Date(System.currentTimeMillis() +3600000*24*365))
                .claim("userId",userId)    //claim： 自定义数据
                .claim("userName",userName)
                .signWith(signingKey)    //设置签名(防伪)
                .compact();


        return token;
    }




    /*
     *  解析token:
     *    1. 验证token是否过期
     *    2. 可以从token中获取登录用户的信息
     *
     * */
    public static  Claims parseToken(String token){
        //根据签名解析token
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parserBuilder().
                    setSigningKey(signingKey).
                    build().parseClaimsJws(token);
        } catch (ExpiredJwtException e) {
            throw  new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (Exception e){
            throw  new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return claimsJws.getBody();

    }
}